<template>
  <div class="fee-statistics-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-actions">
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出报表
        </el-button>
        <el-button type="success" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计概览卡片 -->
    <div class="statistics-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon income">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">总收入</div>
                <div class="stat-value">¥{{ formatAmount(statistics.totalIncome) }}</div>
                <div class="stat-trend">
                  <span :class="statistics.incomeGrowth >= 0 ? 'up' : 'down'">
                    {{ statistics.incomeGrowth >= 0 ? '+' : '' }}{{ statistics.incomeGrowth }}%
                  </span>
                  较上月
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon payment">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">缴费率</div>
                <div class="stat-value">{{ statistics.paymentRate }}%</div>
                <div class="stat-trend">
                  <span :class="statistics.paymentRateGrowth >= 0 ? 'up' : 'down'">
                    {{ statistics.paymentRateGrowth >= 0 ? '+' : '' }}{{ statistics.paymentRateGrowth }}%
                  </span>
                  较上月
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon overdue">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">逾期率</div>
                <div class="stat-value">{{ statistics.overdueRate }}%</div>
                <div class="stat-trend">
                  <span :class="statistics.overdueRateGrowth <= 0 ? 'up' : 'down'">
                    {{ statistics.overdueRateGrowth >= 0 ? '+' : '' }}{{ statistics.overdueRateGrowth }}%
                  </span>
                  较上月
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon count">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">账单数</div>
                <div class="stat-value">{{ statistics.totalCount }}</div>
                <div class="stat-trend">
                  <span :class="statistics.countGrowth >= 0 ? 'up' : 'down'">
                    {{ statistics.countGrowth >= 0 ? '+' : '' }}{{ statistics.countGrowth }}%
                  </span>
                  较上月
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" @submit.prevent="handleFilter">
        <el-form-item label="社区">
          <el-select
            v-model="filterForm.communityId"
            placeholder="请选择社区"
            clearable
            @change="handleCommunityChange"
            style="width: 200px"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="费用类型">
          <el-select
            v-model="filterForm.feeType"
            placeholder="请选择费用类型"
            clearable
            style="width: 150px"
          >
            <el-option label="物业费" :value="1" />
            <el-option label="水费" :value="2" />
            <el-option label="电费" :value="3" />
            <el-option label="燃气费" :value="4" />
            <el-option label="卫生费" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图表展示 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <!-- 收入趋势图 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <div class="chart-header">
                <span>收入趋势</span>
                <el-radio-group v-model="trendChartType" size="small">
                              <el-radio-button value="month">月度</el-radio-button>
            <el-radio-button value="week">周度</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container">
              <div ref="trendChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 费用类型分布 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <div class="chart-header">
                <span>费用类型分布</span>
              </div>
            </template>
            <div class="chart-container">
              <div ref="pieChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 社区对比 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <div class="chart-header">
                <span>社区收入对比</span>
              </div>
            </template>
            <div class="chart-container">
              <div ref="communityChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 缴费状态统计 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <div class="chart-header">
                <span>缴费状态统计</span>
              </div>
            </template>
            <div class="chart-container">
              <div ref="statusChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="table-header">
          <span>详细统计数据</span>
          <el-button type="primary" size="small" @click="exportTableData">
            导出表格
          </el-button>
        </div>
      </template>
      
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="communityName" label="社区" width="120" />
        <el-table-column prop="feeTypeName" label="费用类型" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="已缴金额" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.paidAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="unpaidAmount" label="未缴金额" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.unpaidAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentRate" label="缴费率" width="100">
          <template #default="{ row }">
            {{ row.paymentRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="totalCount" label="账单数" width="100" />
        <el-table-column prop="paidCount" label="已缴数" width="100" />
        <el-table-column prop="unpaidCount" label="未缴数" width="100" />
        <el-table-column prop="overdueCount" label="逾期数" width="100" />
        <el-table-column prop="feeMonth" label="计费月份" width="120" />
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Money, Check, Warning, Document, Download, Refresh } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { propertyFeeApi } from '@/api/property'
import { showMessage } from '@/utils/message'

// 作者: Wu.Liang

// 响应式数据
const loading = ref(false)
const tableLoading = ref(false)
const trendChartType = ref('month')
const dateRange = ref<string[]>([])

// 筛选表单
const filterForm = reactive({
  communityId: undefined,
  feeType: undefined,
  startDate: '',
  endDate: ''
})

// 统计数据
const statistics = reactive({
  totalIncome: 0,
  incomeGrowth: 0,
  paymentRate: 0,
  paymentRateGrowth: 0,
  overdueRate: 0,
  overdueRateGrowth: 0,
  totalCount: 0,
  countGrowth: 0
})

// 表格数据
const tableData = ref([])
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 选项数据
const communityList = ref([])

// 图表实例
let trendChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null
let communityChart: echarts.ECharts | null = null
let statusChart: echarts.ECharts | null = null

// 生命周期
onMounted(() => {
  loadData()
  initCharts()
})

// 方法定义
const loadData = async () => {
  try {
    loading.value = true
    await Promise.all([
      loadStatistics(),
      loadTableData(),
      loadCommunityList()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
    showMessage({ type: 'error', message: '加载数据失败' })
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    const params = {
      communityId: filterForm.communityId,
      feeType: filterForm.feeType,
      startDate: filterForm.startDate,
      endDate: filterForm.endDate
    }
    
    const response = await propertyFeeApi.getPropertyFeeStatistics(params)
    if (response.code === 200) {
      Object.assign(statistics, response.data)
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadTableData = async () => {
  try {
    tableLoading.value = true
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      communityId: filterForm.communityId,
      feeType: filterForm.feeType,
      startDate: filterForm.startDate,
      endDate: filterForm.endDate
    }
    
    const response = await propertyFeeApi.getPropertyFeeStatistics(params)
    if (response.code === 200) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
    }
  } catch (error) {
    console.error('加载表格数据失败:', error)
  } finally {
    tableLoading.value = false
  }
}

const loadCommunityList = async () => {
  try {
    const response = await propertyFeeApi.getCommunityList()
    if (response.code === 200) {
      communityList.value = response.data
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
  }
}

const initCharts = async () => {
  await nextTick()
  
  // 初始化趋势图
  const trendChartDom = document.querySelector('.chart') as HTMLElement
  if (trendChartDom) {
    trendChart = echarts.init(trendChartDom)
    renderTrendChart()
  }
  
  // 初始化饼图
  const pieChartDom = document.querySelectorAll('.chart')[1] as HTMLElement
  if (pieChartDom) {
    pieChart = echarts.init(pieChartDom)
    renderPieChart()
  }
  
  // 初始化社区对比图
  const communityChartDom = document.querySelectorAll('.chart')[2] as HTMLElement
  if (communityChartDom) {
    communityChart = echarts.init(communityChartDom)
    renderCommunityChart()
  }
  
  // 初始化状态统计图
  const statusChartDom = document.querySelectorAll('.chart')[3] as HTMLElement
  if (statusChartDom) {
    statusChart = echarts.init(statusChartDom)
    renderStatusChart()
  }
}

const renderTrendChart = () => {
  if (!trendChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['收入', '缴费数']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: [
      {
        type: 'value',
        name: '收入(元)',
        position: 'left'
      },
      {
        type: 'value',
        name: '缴费数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '收入',
        type: 'line',
        data: [12000, 15000, 18000, 16000, 20000, 22000],
        smooth: true
      },
      {
        name: '缴费数',
        type: 'bar',
        yAxisIndex: 1,
        data: [120, 150, 180, 160, 200, 220]
      }
    ]
  }
  
  trendChart.setOption(option)
}

const renderPieChart = () => {
  if (!pieChart) return
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '费用类型',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 40, name: '物业费' },
          { value: 25, name: '水费' },
          { value: 20, name: '电费' },
          { value: 10, name: '燃气费' },
          { value: 5, name: '卫生费' }
        ]
      }
    ]
  }
  
  pieChart.setOption(option)
}

const renderCommunityChart = () => {
  if (!communityChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['收入', '缴费率']
    },
    xAxis: {
      type: 'category',
      data: ['社区A', '社区B', '社区C', '社区D']
    },
    yAxis: [
      {
        type: 'value',
        name: '收入(万元)'
      },
      {
        type: 'value',
        name: '缴费率(%)',
        max: 100
      }
    ],
    series: [
      {
        name: '收入',
        type: 'bar',
        data: [50, 60, 45, 70]
      },
      {
        name: '缴费率',
        type: 'line',
        yAxisIndex: 1,
        data: [85, 90, 80, 95]
      }
    ]
  }
  
  communityChart.setOption(option)
}

const renderStatusChart = () => {
  if (!statusChart) return
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '缴费状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 80, name: '已缴费' },
          { value: 15, name: '未缴费' },
          { value: 5, name: '逾期' }
        ]
      }
    ]
  }
  
  statusChart.setOption(option)
}

const handleFilter = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(filterForm, {
    communityId: undefined,
    feeType: undefined,
    startDate: '',
    endDate: ''
  })
  dateRange.value = []
  pagination.current = 1
  loadData()
}

const handleCommunityChange = () => {
  loadData()
}

const handleDateRangeChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    filterForm.startDate = dateRange.value[0]
    filterForm.endDate = dateRange.value[1]
  } else {
    filterForm.startDate = ''
    filterForm.endDate = ''
  }
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadTableData()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadTableData()
}

const handleRefresh = () => {
  loadData()
}

const handleExport = () => {
  showMessage({ type: 'success', message: '导出功能开发中' })
}

const exportTableData = () => {
  showMessage({ type: 'success', message: '表格导出功能开发中' })
}

const formatAmount = (amount: number) => {
  return amount ? amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 }) : '0.00'
}

// 监听窗口大小变化，重新渲染图表
window.addEventListener('resize', () => {
  trendChart?.resize()
  pieChart?.resize()
  communityChart?.resize()
  statusChart?.resize()
})
</script>

<style lang="scss" scoped>
.fee-statistics-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.statistics-overview {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #fff;

    &.income {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.payment {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.overdue {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }

    &.count {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
  }

  .stat-info {
    flex: 1;
  }

  .stat-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
  }

  .stat-trend {
    font-size: 12px;
    color: #909399;

    .up {
      color: #67c23a;
    }

    .down {
      color: #f56c6c;
    }
  }
}

.filter-card {
  margin-bottom: 20px;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .chart-container {
    height: 300px;
  }

  .chart {
    width: 100%;
    height: 100%;
  }
}

.table-card {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 